/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 9/20/13
 * Time: 10:20 AM
 * To change this template use File | Settings | File Templates.
 */
package com.societyGames.codeAlong.state.codeExercise.model
{
import com.societyGames.system.FileCache;

import flash.display.Loader;
import flash.display.Stage;
import flash.events.Event;
import flash.system.System;
import flash.utils.ByteArray;

public class TestCaseUnloadTest
{
  //private var _caseApplicationDomain:ApplicationDomain;
  private var _caseLoader:Loader;
  private var _fileCache:FileCache;
  private var _testCaseByteArray:ByteArray;
  private var _stage:Stage;

  public function TestCaseUnloadTest(stage:Stage)
  {
    _stage = stage;
  }

  public function test():void
  {
    _fileCache = new FileCache();
    _fileCache.load("RobotZero/RobotZeroContainer.swf", onFileLoaded);
  }

  private function onFileLoaded(url:String, byteArray:ByteArray):void
  {
    _testCaseByteArray = byteArray;

    trace("Before");
    gc();

    loadCase();
  }

  private function gc():void
  {
    trace(System.privateMemory);
    System.gc();
    trace(System.privateMemory);
  }

  private function loadCase():void
  {
    //_caseApplicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
    //var caseLoaderContext:LoaderContext = new LoaderContext(false, _caseApplicationDomain);
    this._caseLoader = new Loader();
    //Listen for everything we need
    //_caseLoader.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, caseUncaughtErrorHandler);
    _caseLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, caseLoadCompleteHandler);
    //Do the actual load of the case.
    // _caseLoader.load(URLRequest("RobotZero/RobotZeroContainer.swf"), caseLoaderContext);
    _caseLoader.loadBytes(_testCaseByteArray/*, caseLoaderContext*/);
  }

  private function unloadCase():void
  {
    _caseLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, caseLoadCompleteHandler);
    //_caseLoader.close();
    _stage.addChild(_caseLoader);
    _caseLoader.unloadAndStop();
    _stage.removeChild(_caseLoader);
    _caseLoader = null;
    //_testCaseByteArray.clear();
    //_testCaseByteArray = null;
    //_caseApplicationDomain = null;
  }

  private function caseLoadCompleteHandler(event:Event):void
  {
    unloadCase();
    /*setInterval(function():void
     {
     trace("After");
     gc();
     }, 5000
     );*/
    trace("After");
    gc();
  }
}
}
